﻿using System;
using System.Collections.Generic;
using System.Collections;

namespace Facebook
{
    /// <summary>
    /// This is the class to instantiate to make facebook calls - it logs in and creates a session in the constructor, 
    /// then offers up some methods to use to retrieve facebook friends data - these can be expanded to make use of the api sections
    /// you want - see: http://wiki.developers.facebook.com/index.php/API
    /// </summary>
    public class API
    {
        // Once retrieve - provide global storage for session information
        private Facebook.auth.getSession sessionInfo;

        /// <summary>
        ///  Constructor
        /// </summary>
        public API()
        {
            sessionInfo = new Facebook.auth.getSession();       // Create the structure to store the session information
            sessionInfo = Facebook.Login.LoginAndGetSession();  // We need somewhere to track the facebook session details
         }

        /// <summary>
        /// Public property to return the session expriry (also handy for checking if the session is valid...
        /// </summary>
        /// <returns></returns>
        public DateTime SessionExpires { get { return sessionInfo.expires_DateTime; } }
        
        /// <summary>
        /// Facebook API call - retrieves user information for a supplied user Id
        /// </summary>
        public Facebook.users.getInfo GetUsersInfo(double userId)
        {   
            var parameters = new SortedDictionary<string, string>();  // Facebook parameter list (key value pair) that (needs to be sorted in order to get the MD5 hash correct - see Facebook.Security
            parameters.Add("method", "facebook.users.getinfo");
            parameters.Add("session_key", sessionInfo.session_key);
            parameters.Add("uids", userId.ToString());
            parameters.Add("fields", "first_name,last_name,pic_big,pic_small,profile_url,status,hs_info,hometown_location");

            string jsonResult = JSON.Helper.StripSquareBrackets(Facebook.Web.SendCallToFacebook(parameters));
            return (JSON.Helper.Deserialize<Facebook.users.getInfo>(jsonResult));
        }

        /// <summary>
        /// Facebook API call - returns an ArrayList of friends of the logged in user
        /// </summary>
        public ArrayList GetListOfFriends()
        {
            var parameters = new SortedDictionary<string, string>();  // Facebook parameter list (key value pair) that (needs to be sorted in order to get the MD5 hash correct - see Facebook.Security
            parameters.Add("method", "facebook.friends.get");
            parameters.Add("session_key", sessionInfo.session_key);
            string jsonResult = Facebook.Web.SendCallToFacebook(parameters);

            ArrayList listOfFriendsUserIds = JSON.Helper.ArrayFromJSON(jsonResult);
            return listOfFriendsUserIds;
        }


        public string PublishStream(string message)
        {
			return PublishStream(message, null);
		}


		public string PublishStream(string message, AttachmentHelper.attachment attachment)
		{
            // Create a token to use for the facebook session
            var parameters = new SortedDictionary<string, string>();  // Facebook parameter list (key value pair) that (needs to be sorted in order to get the MD5 hash correct - see Facebook.Security
            parameters.Add("method", "facebook.stream.publish"); // http://wiki.developers.facebook.com/index.php/Stream.publish

            parameters.Add("session_key", sessionInfo.session_key);
           
			if(!string.IsNullOrEmpty((message)))
				parameters.Add("message", message);


			if (attachment != null)
			{
				var mediaList = new List<string>();

				if (attachment.media != null)
				{
					foreach (var item in attachment.media)
					{
						var media = new Dictionary<string, string>{
                               {"type", item.type.ToString()}
                                };
						if (item.type == AttachmentHelper.attachment_media_type.image)
						{
							var image = item as AttachmentHelper.attachment_media_image;
							media.Add("src", image.src);
							media.Add("href", image.href);
						}
						mediaList.Add(Helpers.ConvertToJSONAssociativeArray(media));
					}

				}
				var dict = new Dictionary<string, string>{
                    {"name", attachment.name},
                    {"href", attachment.href},
                    {"caption", attachment.caption},
                    {"description", attachment.description},
                    {"media", Helpers.ConvertToJSONArray(mediaList)}
                };
				parameters.Add("attachment", Helpers.ConvertToJSONAssociativeArray(dict));
			}

            //parameters.Add("action_links", null);
            parameters.Add("target_id", sessionInfo.uid.ToString());
            parameters.Add("uid", "0");

            //////    string response = serviceComponent.API.stream.publish("WEI test message goes here", null, null, uid.ToString(), 0);
            string jsonResult = Facebook.Web.SendCallToFacebook(parameters, sessionInfo);
            return JSON.Helper.StripSingleResult(jsonResult); // Return the result
        }
    }
}
